<?php
/**
 * Created by PhpStorm.
 * User: TangYijun
 * Date: 2017/4/27
 * Time: 9:42
 */
namespace app\admin\controller;
use app\data\Data;
use app\validate\ArticleValidate;
use think\Config;
use think\Request;

/**
 * ----------------------------------
 * Class Article
 * @package app\admin\controller
 * 文章模型
 * ----------------------------------
 */
class Article extends Check{
    /**
     * @return \think\response\View
     * 文章列表
     */
    public function articleList(){
        $article = new Data('article');
        $where = 'a.id > 0';
        $get = input('param.');
        if(!empty($get['search'])){
            $where .= " and title like '%{$get['search']}%'";
            $this->assign('search',$get['search']);
        }
        $list = $article->page($where,"is_top desc,update_time desc,create_time desc",Config::get('paginate.list_rows'),$get,[['type b','a.type_id = b.id','LEFT']],"a.*,b.type_name",$get['page']);
        return view('articleList',['list'=>$list->items(),'page'=>$list->render()]);
    }
    /**
     * @return array|\think\response\View
     * 添加文章
     */
    public function articleAdd(){
        try{
            $type = new Data('type');
            if(Request::instance()->isPost()){
                $article = new Data('article');
                $post = Request::instance()->post();
                $tag_ids = $post['tag_ids'];  //选择的标签
                unset($post['tag_ids']);
                $rule_validate = new ArticleValidate();
                $rule_validate = $rule_validate->articleValidate();
                self::validateData($rule_validate['rule'],$rule_validate['message'],$post);
                if(!empty($_FILES)){
                    $post['image'] = upload(); //图片上传
                }
                $post['introduction'] = \think\Helper::articleStripTags($post['content']);
                $post['create_time'] = time();
                $article->startTrans();   //开启事务
                $article_id  = $article->insertData($post);
                $arr_tag_ids = \think\Helper::articleTag($tag_ids,$article_id); //组合数组
                $article_tag = new Data('article_tag');
                $article_tag_bool = $article_tag->insertAll($arr_tag_ids);
                if(!$article_id || !$article_tag_bool){
                    $article->rollback();//事务回滚
                    throw new \LogicException(Config::get('error_table.error')['msg'],Config::get('error_table.error')['code']);
                }
                $article->commit(); //提交事务
                return self::formatSuccessResult();
            }
        }catch(\Exception $e){
            return self::formatResult($e->getCode(),$e->getMessage());
        }
        $type_list = $type->selectData("model_id = 1");
        $type_list = infinite($type_list,0,0);
        $tag = new Data('tag');
        $tag_list = $tag->selectData();//读取所有的标签
        return view('articleAdd',['type_list'=>$type_list,'tag_list'=>$tag_list]);
    }

    /**
     * @return \think\response\View
     * 修改文章
     */
    public function articleSave(){
        $type = new Data('type');
        $article = new Data('article');
        $article_tag = new Data('article_tag'); 
        try{
            if(Request::instance()->isPost()){
                $post = Request::instance()->post();
                $tag_ids = $post['tag_ids'];  //选择的标签
                unset($post['tag_ids']);
                $rule_validate = new ArticleValidate();
                $rule_validate = $rule_validate->articleValidate();
                self::validateData($rule_validate['rule'],$rule_validate['message'],$post);
                if(!empty($_FILES)){
                    $post['image'] = upload(); //图片上传
                }else{
                    unset($post['image']);
                }
                $post['update_time'] = time();
                $post['content'] = str_replace("a href",'a target="_blank" href',$post['content']) ; //更改a标签为打开新页面              
                $post['introduction'] = \think\Helper::articleStripTags($post['content']);
                $article->startTrans();
                $article_save_bool = $article->updateData($post);
                $tag_delete_bool = $article_tag->deleteByWhere("article_id = {$post['id']}");     //删除该文章原来的标签
                $arr_tag_ids = \think\Helper::articleTag($tag_ids,$post['id']);                   //组合数组
                $article_tag_bool = true;
                if(!empty($arr_tag_ids)){
                    $article_tag_bool = $article_tag->insertAll($arr_tag_ids);                        //重新插入新的标签
                }
                if($article_save_bool === false || !$tag_delete_bool || !$article_tag_bool){
                    $article->rollback();
                    throw new \LogicException(Config::get('error_table.error')['msg'],Config::get('error_table.error')['code']);
                }
                $article->commit();
                return self::formatSuccessResult();
            }
        }catch(\Exception $e){
            return self::formatResult($e->getCode(),$e->getMessage());
        }
        $id = intval(input('param.id'));
        $getOne = $article->find("id = $id");
        $type_list = $type->selectData("model_id = 1");
        $type_list = infinite($type_list,0,0);                           //递归+deep
        $tag = new Data('tag');
        $tag_list = $tag->selectData();                                  //读取所有的标签
        $tag_ids = $article_tag->selectData("article_id = $id","tag_id");//查询该文章对应的tag_id
        $tag_ids = \think\Helper::implodeTag($tag_ids);                  //对标签的ID进行处理
        return view('articleSave',['type_list'=>$type_list,'one'=>$getOne,'tag_list'=>$tag_list,'tag_ids'=>$tag_ids]);
    }

    /**
     * @return array
     * 置顶和取消置顶操作
     */
    public function articleTop(){
        try{
            if(Request::instance()->isPost()){
                $post = Request::instance()->post();
                $article = new Data('article');
                if($post['top'] == $article::TOP_YES){
                    $data = ['is_top'=>$article::TOP_YES,'update_time'=>time()];
                }
                if($post['top'] == $article::TOP_NOT){
                    $data = ['is_top'=>$article::TOP_NOT,'update_time'=>time()];
                }
                if($article->setField("id = {$post['id']}",$data)===false){
                    throw new \LogicException(Config::get('error_table.error')['msg'],Config::get('error_table.error')['code']);
                }
            }
        }catch(\Exception $e){
            return self::formatResult($e->getCode(),$e->getMessage());
        }
        return self::formatSuccessResult();
    }
    /**
     * @return array
     * 删除文章和对应的标签数据
     */
    public function articleDelete(){
        try{
            $id = intval(input('id'));
            $article = new Data('article');
            $article_tag = new Data('article_tag');
            $article->startTrans(); //开启事务
            $delete_article_bool = $article->deleteDaPtaByPrimaryKey($id);
            $delete_tag_bool = $article_tag->deleteByWhere("article_id = $id");
            if(!$delete_article_bool || !$delete_tag_bool){
                $article->rollback();
                throw new \LogicException(Config::get('error_table.error')['msg'],Config::get('error_table.error')['code']);
            }
        }catch(\Exception $e){
            return self::formatResult($e->getCode(),$e->getMessage());
        }
        $article->commit();
        return self::formatSuccessResult();
    }

}